<?php

/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\note;

use app\api\model\dao\Note;
use app\api\model\dao\NoteReply;
use app\api\model\dao\NoteReplyReply;
use app\api\model\dao\TaskLog;
use app\api\model\dao\UpRank;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserCurrency;
use app\api\model\data\currency\ConsumeCurrency;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class NoteReplyAnswer extends PageBase
{

    private $objNote;
    private $objNoteReply;
    private $objNoteReplyReply;
    private $objTaskLog;
    private $objUserCurrency;
    private $objUpRank;
    private $objUserAccount;

    public function __construct()
    {
        parent::__construct();

        $this->objNote = new Note();
        $this->objNoteReply = new NoteReply();
        $this->objNoteReplyReply = new NoteReplyReply();
        $this->objTaskLog = new TaskLog();
        $this->objUserCurrency = new ConsumeCurrency();
        $this->objUpRank = new UpRank();
        $this->objUserAccount = new UserAccount();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'note_id' => 'require',
            'reply_id' => 'require',
            'userid' => 'require',
            'content' => 'require',
        ];
        $msg = [
            'note_id.require' => '帖子id不能为空',
            'reply_id.require' => '请选择回复的评论',
            'userid.require' => '请选择评论对象',
            'content.require' => '回复内容不能为空',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function myExcute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            throw new Exception('check token fail...', Error::ERR_NO_AUTH);
        }

        // 1、获取用户信息
        $user_account = $this->objUserAccount->getUserAccount(['user_id' => $this->user_id]);
        if (false === $user_account) {
            Log::error(__METHOD__ . 'get user account from db fail. [user_id: ' . $param['user_id'] . ']');
            return $this->getRes(Error::ERR_SYS);
        }
        if (empty($user_account)) {
            return $this->getRes(Error::ERR_USER_NOT_EXIST);
        }
        $user_account = $user_account[0];

        if ($user_account['silence_time'] > time()) {
            return $this->getRes(Error::ERR_USER_IS_SILENCE);
        }

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            throw new Exception($ret, Error::ERR_PARAM);
        }

        // 2、从数据库中获取帖子详情
        $ret = $this->getNoteInfoFromDB($param['note_id']);
        if (false === $ret) {
            throw new Exception('get note info from db fail. [note_id: ' . $param['note_id'] . ']', Error::ERR_SYS);
        }

        if (empty($ret)) {
            throw new Exception('note info is empty. [note_id: ' . $param['note_id'] . ']', Error::ERR_NOTE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_NOTE_DELETED == $ret['is_delete']) {
            throw new Exception('note is deleted', Error::ERR_NOTE_DELETED);
        }

        // 5、构造参数
        $input = [
            'note_id' => intval($param['note_id']),
            'reply_id' => intval($param['reply_id']),
            'note_userid' => $ret['creator'],
            'userid' => $this->user_id,
            'recv_userid' => $param['userid'],
            'content' => trim($param['content']),
            'create_time' => time(),
        ];

        $add_ret = $this->objNoteReplyReply->add($input);
        if (false === $add_ret) {
            throw new Exception('add note praise fail...[input: ' . json_encode($input) . ']', Error::ERR_SYS);
        }
    }

    /**
     * 从数据库中获取帖子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getNoteInfoFromDB($note_id)
    {
        if (!$note_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $note_id]
        ];
        $ret = $this->objNote->getNote($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        $ret = $ret[0];
        return $ret;
    }

    public function task($userid)
    {

        $date = date('Ymd');

        $arrCond = [
            'task_id' => ['=', 3],
            'userid' => $userid,
        ];
        $ret = $this->objTaskLog->getTaskLog($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            // 判断是否满足完成任务条件
            $note_reply_cnt = $this->objNoteReply->getNoteReplyCountByUserid($userid);
            if ($note_reply_cnt >= Flag::CONST_TASK_NEW_NOTE_REPLY_COUNT) {
                $arrInput = [
                    'task_id' => 3,
                    'userid' => $userid,
                    'date' => $date,
                ];
                $ret = $this->objTaskLog->addTaskLog($arrInput);
                if (false === $ret) {
                    return false;
                }
                $ret = $this->objUserCurrency->addCurrency($userid, 50, Flag::CURENCY_TYPE_INTEGRAL, Flag::CURRENCY_EXCHANGE_TYPE_BUY_TASK);
                if (false === $ret) {
                    return false;
                }
            }
        }

        $arrCond = [
            'task_id' => ['=', 101],
            'userid' => $userid,
            'date' => $date,
        ];
        $ret = $this->objTaskLog->getTaskLog($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            // 判断是否满足完成任务条件
            $note_reply_cnt = $this->objNoteReply->getNoteReplyCountByUserid($userid, $date);
            if ($note_reply_cnt >= Flag::CONST_TASK_DAILY_NOTE_REPLY_COUNT) {
                $arrInput = [
                    'task_id' => 101,
                    'userid' => $userid,
                    'date' => $date,
                ];
                $ret = $this->objTaskLog->addTaskLog($arrInput);
                if (false === $ret) {
                    return false;
                }
                $ret = $this->objUserCurrency->addCurrency($userid, 10, Flag::CURENCY_TYPE_INTEGRAL, Flag::CURRENCY_EXCHANGE_TYPE_BUY_TASK);
                if (false === $ret) {
                    return false;
                }
            }
        }
    }
}
